<?php

/**
 *	Form Builder Library - simplifies management and loading of forms in CodeIgniter applications
 *
 * @version		  0.1
 * @last_update September 1, 2007  
 * @package		  CodeIgniter
 * @subpackage	Form Builder Library
 * @category    Output
 * @author		  Tim Wood [codearachnid]
 * @link		    http://code.codearachnid.com
 
CREATE TABLE `forms` (
`form_id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`last_updated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL ,
`form_slug` VARCHAR( 100 ) NOT NULL,
`form_action` VARCHAR( 100 ) NULL,
`form_name` VARCHAR( 100 ) NULL ,
`form_status` ENUM( 'active', 'inactive' ) NOT NULL DEFAULT 'active'
) ENGINE = MYISAM ;

CREATE TABLE `form_fields` (
`form_field_id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`last_updated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL ,
`form_id` INT( 11 ) NOT NULL ,
`field_type` VARCHAR( 30 ) NOT NULL,
`field_slug` VARCHAR( 100 ) NOT NULL,
`field_table` VARCHAR( 100 ) NOT NULL,
`field_name` VARCHAR( 100 ) NULL,
`field_description` MEDIUMTEXT NULL,
`field_value` MEDIUMTEXT NULL,
`field_default` MEDIUMTEXT NULL ,
`field_validation` MEDIUMTEXT NULL ,
`field_status` ENUM( 'active', 'inactive' ) NOT NULL DEFAULT 'active',
`field_order` INT( 3 ) NOT NULL
) ENGINE = MYISAM ;

 *
 *
 */

class Formbuilder {
	var $CI;
	var $debug = TRUE;
	var $fieldtypes = array('input','checkbox','dropdown','hidden','textarea','radio','file','button','image');
	var $reserved = array('fieldset','/fieldset','separator','linebreak','submit','button');
	
	function Formbuilder($config = array()) {
		$this->CI =& get_instance();
	}
  
  /*
   *
   * validate the submission
   *
   */         
  function validate() {
  }

  /*
   *
   * build form   
   *
   */ 
  function build($form_slug, $form_action = '', $form_attributes = array(), $field_attributes = array(), $form_values = array()) {
    // load resources
    $this->CI->load->helper('form');
    $this->CI->load->helper('form_ext');  
    $this->CI->lang->load('formbuilder');
    $form_query = $this->CI->db->getwhere('forms', array('form_slug' => $form_slug, 'form_status' => 'active'));
    if ($form_query->num_rows() > 0) {
      $form = $form_query->row_array();
      $this->CI->db->from('form_fields')->where(array('form_id' => $form['form_id'], 'field_status' => 'active'))->orderby('field_order','asc');
      $field_query = $this->CI->db->get();
      if ($field_query->num_rows() > 0) {
        $fields = $field_query->result_array();
        $validate = FALSE;
        $fieldset_open = FALSE;
        $form_action = (isempty($form_action)) ? $form['form_action'] : $form_action;
        $html_form = form_open_multipart($form_action, $form_attributes);
        foreach($fields as $field) {
          // build label for form element
          if(!in_array($field['field_type'], $this->reserved)) {
            if($field['field_validation'] == 'required') {
              $validate = TRUE;
              $html_form .= ' '.form_label(array('for' => $field['field_slug'], 'label' => $field['field_name'].'*:')).' ';
            } else {
              $html_form .= ' '.form_label(array('for' => $field['field_slug'], 'label' => $field['field_name'].':')).' ';
            }
          }
          // build form element
          switch($field['field_type']) {
            case 'fieldset':
              $html_form .= form_fieldset('open', $field['field_name']);
              $fieldset_open = TRUE;
              break;
            case 'dropdown':
              eval('$values = '.$field['field_value'].';');
              $html_form .= (isset($form_values[$field['field_slug']])) 
                    ? form_dropdown($field['field_slug'], $values, $form_values[$field['field_slug']])
                    : form_dropdown($field['field_slug'], $values);
              break;
            case 'input':
              $field_data = (isset($form_values[$field['field_slug']])) 
                    ? array('name'  => $field['field_slug'],
                            'id'    => $field['field_slug'],
                            'value' => $form_values[$field['field_slug']])
                    : array('name'  => $field['field_slug'],
                            'id'    => $field['field_slug']);
              $input = array_merge($field_data, $field_attributes);
              $html_form .= form_input($input);
              break;
            default:
              break;
          }
        }
        if ($validate) $html_form .= '<div class="form_validate_lang">'.$this->CI->lang->line('form_validate_confirm').'</div>';
        // last minute cleanup of open tags
        if($fieldset_open) $html_form .= form_fieldset();
        $html_form .= form_close();
        return $html_form;
      } else {
        return $this->CI->lang->line('err_no_fields', $form_slug);
      }
    } else {
      return $this->CI->lang->line('err_no_form', $form_slug);
    }
  }

	/*
	 * 
	 * used to evaluate blank entries
	 * 
	 */
	function isempty($var) {
	    if (((is_null($var) || rtrim($var) == "") && $var !== false) || (is_array($var) && empty($var))) {
	        return true;
	    } else {
	        return false;
	    }
	}


}

?>
